const cron = require('node-cron');
const OrderStatusService = require('../services/orderStatusService');
const logger = require('../utils/logger');

class OrderTimeoutJob {
  /**
   * 启动定时任务
   */
  static start() {
    // 每5分钟检查一次超时订单
    cron.schedule('*/5 * * * *', async () => {
      try {
        logger.info('开始检查超时订单...');
        
        const result = await OrderStatusService.handleTimeoutOrders();
        
        if (result.data.cancelled > 0 || result.data.failed > 0) {
          logger.info(`超时订单处理完成: ${result.message}`);
        }
      } catch (error) {
        logger.error('定时处理超时订单失败:', error);
      }
    }, {
      scheduled: true,
      timezone: 'Asia/Shanghai'
    });
    
    logger.info('订单超时检查定时任务已启动 (每5分钟执行一次)');
  }

  /**
   * 停止定时任务
   */
  static stop() {
    cron.getTasks().forEach(task => {
      task.stop();
    });
    
    logger.info('订单超时检查定时任务已停止');
  }
}

module.exports = OrderTimeoutJob;